package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.dao.OrdersettingDao;
import com.atguigu.pojo.OrderSetting;
import com.atguigu.service.OrdersettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * OrdersettingServiceImpl
 *
 * @Author: 马伟奇
 * @CreateTime: 2021-02-01
 * @Description:
 */
@Service(interfaceClass = OrdersettingService.class)
@Transactional
public class OrdersettingServiceImpl implements OrdersettingService {

    @Autowired
    private OrdersettingDao ordersettingDao;

    @Override
    public void add(List<OrderSetting> orderSettings) {
        for (OrderSetting orderSetting : orderSettings) {
            // 在添加之前，需要查询数据库
            // 根据当前的日期进行查询，如果有数据，直接更新数据，如果没有数据在进行添加
            long count =  ordersettingDao.findCountByOrderDate(orderSetting.getOrderDate());
            if (count > 0){
                // 更新数据
                ordersettingDao.editNumberByOrderDate(orderSetting);
            }else {
                // 添加数据
                ordersettingDao.add(orderSetting);
            }

        }

    }

    // 2020-02
    @Override
    public List<Map> getOrderSettingByMonth(String date) {
        // 开始日期 2020-02-01
        String dateBegin = date + "-01";

        // 结束日期 2020-02-28
        String dateEnd = date + "-31";

        Map<String, Object> map = new HashMap<>();
        map.put("dateBegin",dateBegin);
        map.put("dateEnd",dateEnd);
        // 查询数据库，查询一个月的数据
        List<OrderSetting> lists =  ordersettingDao.getOrderSettingByMonth(map);
        // this.leftobj = [
        //     { date: 1, number: 120, reservations: 1 },
        //     { date: 3, number: 120, reservations: 1 },
        //     { date: 4, number: 120, reservations: 120 },
        //     { date: 6, number: 120, reservations: 1 },
        //     { date: 8, number: 120, reservations: 1 }
        // ];
        List<Map> OrderSettingLists = new ArrayList<>();
        for (OrderSetting orderSetting : lists) {
            Map data = new HashMap<>();
            data.put("date",orderSetting.getOrderDate().getDate());
            data.put("number",orderSetting.getNumber());
            data.put("reservations",orderSetting.getReservations());
            OrderSettingLists.add(data);
        }


        return OrderSettingLists;
    }

    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        // 在添加之前，需要查询数据库
        // 根据当前的日期进行查询，如果有数据，直接更新数据，如果没有数据在进行添加
        long count =  ordersettingDao.findCountByOrderDate(orderSetting.getOrderDate());
        if (count > 0){
            // 更新数据
            ordersettingDao.editNumberByOrderDate(orderSetting);
        }else {
            // 添加数据
            ordersettingDao.add(orderSetting);
        }
    }
}